﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using He.Common;
using System.IO;

namespace He.Web.user
{
    public partial class pwd_find : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void btnSend_Click(object sender, EventArgs e)
        {
            Model.site_info SiteInfo = new BLL.site_info().GetModelByLang("cn");
            Model.webset SiteConfig = new BLL.webset().GetWebset();

            //检查验证码
            string checkcode = txtCheckcode.Text;
            if (Session["VerifyCode"] == null)
            {
                lblMsg.Text = "验证码已过期";
                return;
            }
            if (Session["VerifyCode"].ToString().ToLower() != checkcode.ToLower())
            {
                lblMsg.Text = "验证码错误，请重新输入";
                return;
            }


            BLL.member mgr = new BLL.member();
            string user_name = txtUserName.Text.Trim();
            string email = txtEmail.Text.Trim();
            if (mgr.ExistsEmail(user_name, email))
            {
                Model.member member = mgr.GetModel(user_name);
                //读取邮件模板
                string email_path = PathHelper.MapPath("~/user/email/pwd_find.html");
                FileStream fs = new FileStream(email_path, FileMode.Open);
                StreamReader sr = new StreamReader(fs);
                string body = sr.ReadToEnd();
                fs.Dispose();
                sr.Dispose();

                string random_code = StringHelper.GeneratePassword(15);//随机码，用于重置密码时校验
                body = body.Replace("{user_email}", email).Replace("{web_name}", SiteInfo.WebName).Replace("{jump_url}", string.Format("<a href='http://{0}/user/pwd_reset.aspx?uid={1}&rid={2}'>http://{0}/user/pwd_reset.aspx?uid={1}&rid={2}</a>", SiteConfig.site_domain.Trim('/'), member.id, random_code)).Replace("{send_ip}", Request.UserHostAddress).Replace("{web_url}", string.Format("<a href='http://{0}'>http://{0}</a>", SiteConfig.site_domain));

                if (EmailHelper.SendEmail("密码找回", SiteConfig.email_id, CryptoHelper.DESDecrypt(SiteConfig.email_pwd), SiteConfig.email_smtpserver, user_name, email, "网站密码找回", body, true))
                {
                    member.reset_key = random_code;
                    member.reset_expires = DateTime.Now.AddDays(3).ToString();//三天后失效
                    mgr.Update(member);
                    lblMsg.Text = "邮件已发送，请查收。如果您没有接收到邮件请将 " + SiteConfig.email_id + " 加入通讯录后再试。";
                }
                else
                {
                    lblMsg.Text = "邮件发送失败，请重试";
                }
            }
            else
            {
                lblMsg.Text = "用户名与邮箱不匹配，请核对后再试";
            }
        }
    }
}